/*
 * Copyright (c) 2012 Robert Burrell Donkin robertburrelldonkin.name
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
 * and associated documentation files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, 
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 
 * is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or 
 * substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * 
 */
package walrus.zip;

import java.io.File;
import java.io.IOException;
import java.util.zip.Deflater;

import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;

import walrus.base.ArticleBuffer;

public class ArchiveSaver {

	private final File archive;

	private ZipArchiveOutputStream out;
	
	private String comment = "Walrus Archive";
	
	private int level = Deflater.BEST_COMPRESSION;
	
	private boolean open = false;
	
	public ArchiveSaver(File archive) {
		super();
		this.archive = archive;
	}

	public ArchiveSaver(String path) {
		this(new File(path));
	}

	public int getLevel() {
		return level;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public String getComment() {
		return comment;
	}

	public void setComment(String comment) {
		this.comment = comment;
	}

	public synchronized void open() throws IOException {
		if (!open) {
			open = true;
			out = new ZipArchiveOutputStream(archive);
			out.setLevel(level);
			out.setFallbackToUTF8(true);
		}
	}
	
	public boolean isOpen() {
		return open;
	}

	public synchronized void save(ArticleBuffer buffer) throws IOException {
		open();
		buffer.saveTo(out);
	}
	
	public synchronized void close() throws IOException {
		if (open) {
			out.setComment(comment);
			out.close();
			open = false;
		}
	}

	@Override
	public String toString() {
		return "ArchiveSaver [archive=" + archive + ", comment=" + comment
				+ ", level=" + level + ", open=" + open + "]";
	}
}
